package com.um.jdy.platform.core.configuration;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.um.jdy.common.platform.entity.po.App;
import com.um.jdy.common.platform.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Component
public class AppConfigure {

    @Autowired
    WxMaService wxMaService;

    @Autowired
    WxPayService wxPayService;

    @Autowired
    AppService appService;

    @PostConstruct
    public void initWxMini() {
        List<App> appList = appService.getListBySql("select * from platform_app where is_delete = '0'",new Object[]{});
        appList.stream().forEach(app -> {
            WxMaDefaultConfigImpl maConfig = new WxMaDefaultConfigImpl();
            maConfig.setAppid(app.getMiniAppId());
            maConfig.setSecret(app.getMiniAppSecrect());

            try {
                wxMaService.addConfig(app.getComId(), maConfig);
                // addConfig有bug，第一个添加的配置不会使用我们指定的id作为key，并且限制了不能设置错误config，这里添加两次
                wxMaService.addConfig(app.getComId(), maConfig);
            } catch (Exception e) {
                log.warn("微信小程序配置错误：{}", e.getMessage());
            }


            WxPayConfig payConfig = new WxPayConfig();
            payConfig.setAppId(app.getMiniAppId());
            payConfig.setMchId(app.getWxMchId());
            payConfig.setApiV3Key(app.getWxApiV3Key());
            payConfig.setPrivateKeyString(app.getWxKeyContent());
            payConfig.setPrivateCertString(app.getWxCertContent());

            try {
                wxPayService.addConfig(app.getComId(), payConfig);
                wxPayService.addConfig(app.getComId(), payConfig);
            } catch (Exception e) {
                log.warn("微信支付配置错误：{}", e.getMessage());
            }


        });
    }
}
